import json
import time
import logging
from pprint import pprint
import requests

urlbase = "https://data-live.flightradar24.com/zones/fcgi/feed.js"
args = "?bounds=40.86,39.03,115.05,117.97&faa=1&satellite=1&mlat=1&flarm=1&adsb=1&gnd=1&air=1&vehicles=1&estimated=1&maxage=14400&gliders=1&stats=1"

dataset = {}
def parse(datalist):
    label = ['ICAO', 'latitude', 'longitude', 'track', 'calibrated altitude(ft)', 'ground speed(kts)', 'unknown1',
             'radar', 'aircraft type', 'aircraft number', 'unknown2', 'src', 'dst', 'flight number', 'zero', 'unknown3',
             'call number', 'zero2', 'flight company']
    assert len(datalist) == len(label), 'datalist length error'
    result = {}
    for k, v in zip(label, datalist):
        result[k] = v
    return result


def pull():
    global dataset
    header = {
        'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
        'origin':'https://www.flightradar24.com',
        'referer':'https://www.flightradar24.com/40.01,116.51/9'
    }
    utc = time.strftime('%Y-%m-%d %X',time.gmtime(time.time()))
    r = requests.get(urlbase + args, headers=header)
    if r.status_code != 200:
        logging.warning("Pull Request Error")
    else:
        content = json.loads(r.content)
        for track in content:
            try:
                id = int(track, 16)
                if id not in dataset:
                    dataset[id] = {}
                dataset[id][utc] = parse(content[track])
            except:
                continue
    return r.status_code


if __name__ == "__main__":
    for t in range(600):
        code = pull()
        print('pull {} time , status = {}'.format(t, code))
        time.sleep(5)
    with open('result.json', 'w') as fout:
        json.dump(dataset, fout)